'''
Author: Logan.Li
Gitee: https://gitee.com/attacker
email: admin@attacker.club
Date: 2024-08-02 01:06:52
LastEditTime: 2024-08-02 01:36:01
Description: 
'''
from proxmoxer import ProxmoxAPI
import warnings
import os
from urllib3.exceptions import InsecureRequestWarning
import logging
from logging.handlers import RotatingFileHandler

# 过滤掉InsecureRequestWarning
warnings.filterwarnings("ignore", category=InsecureRequestWarning)

# 配置日志
logger = logging.getLogger()
logger.setLevel(logging.INFO)
log_file = '/tmp/stop.log'
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler = RotatingFileHandler(log_file, maxBytes=100*1024*1024, backupCount=2)
file_handler.setFormatter(log_formatter)
logger.addHandler(file_handler)

# 创建控制台处理程序
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
logger.addHandler(console_handler)

password = os.environ.get('PASSWORD', '123456')  # 读取环境变量,默认密码123456

# 初始化ProxmoxAPI实例
proxmox = ProxmoxAPI(
    "10.10.10.5",  # 替换为您的Proxmox节点IP地址
    user="root@pam",  # 替换为您的Proxmox用户名和节点名称
    password=password,  # 替换为您的Proxmox密码
    verify_ssl=False  # 如果您的Proxmox节点使用的是自签名证书，需要设置为False
)

for node in proxmox.nodes.get():
    # GET /api2/json/nodes/{node}/qemu
    for vm in proxmox.nodes(node["node"]).qemu.get():
        vmid = vm['vmid'] # 虚拟机id
        vm_config = proxmox.nodes(node["node"]).qemu(vmid).config.get() #  GET /api2/json/nodes/{node}/qemu/{vmid}/config
        print(f"Id:{vmid} {vm['name']} => {vm['status']} 是否开机自启: {vm_config.get('onboot')}")
 
        if not vm.get('template') : # 排除模版实例，判断启用开机自启
          
            message = f"{node['node']} 节点  虚拟机:{vm['name']} 尝试关闭..."
            logging.info(message)
            # print(message)
            # POST /api2/json/nodes/{node}/qemu/{vmid}/status/start
            proxmox.nodes(node["node"]).qemu(vmid).status.stop.post()